
namespace TFSChangeLog.Operations.Command
{
    using System;
    using System.Windows.Input;
    using TFSChangeLog.ViewModel;

    /// <summary>Summary description for <see cref="CancelCommand"/> class.</summary>
    public class CancelCommand : ICommand
    {
        #region Fields

        /// <summary>Summary description for class level field of type <c>TFSChangeLog.ViewModel.ProgressDialogViewModel</c>.</summary>
        private ProgressDialogViewModel m_ViewModel;

        #endregion

        #region Constructor

        /// <summary>Initializes a new instance of the <see cref="CancelCommand"/> class.
        /// CancelCommand Default constructor.</summary>
        /// <param name="viewModel">TODO: Summary description for <c>viewModel</c> parameter of type <c>TFSChangeLog.ViewModel.ProgressDialogViewModel</c>.</param>
        public CancelCommand(ProgressDialogViewModel viewModel)
        {
            this.m_ViewModel = viewModel;
        }

        #endregion

        #region ICommand Members

        /// <summary>
        /// CancelCommand is always enabled as we return true as default value.
        /// </summary>
        /// <returns>TODO: returns an object of type <c>bool</c>.</returns>
        /// <param name="parameter">TODO: Summary description for <c>parameter</c> parameter of type <c>object</c>.</param>
        public bool CanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// Actions to take when CanExecute() changes.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// Executes the CancelCommand for ProgressDialogViewModel
        /// </summary>
        /// <param name="parameter">TODO: Summary description for <c>parameter</c> parameter of type <c>object</c>.</param>
        public void Execute(object parameter)
        {
            if (this.m_ViewModel.IsCancelled)
            {
                return;
            }

            if (this.m_ViewModel.TokenSource == null)
            {
                throw new ApplicationException("progressDialogViewModel.TokenSource property is null");
            }

            this.m_ViewModel.TokenSource.Cancel(true);
            this.m_ViewModel.ShowCancellationMessage();
        }

        #endregion
    }
}